using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
namespace FastNet.WebApi.Extensions;

public static class JwtAuthenticationExt
{
    public static void AddAuthenticationExt(this IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                SaveSigninToken = true,//保存token,后台验证token是否生效(重要)
                ValidateIssuer = true,//是否验证Issuer
                ValidateAudience = true,//是否验证Audience
                ValidateLifetime = true,//是否验证失效时间
                ValidateIssuerSigningKey = true,//是否验证SecurityKey
                ValidAudience = AppSetting.GetSection("Secret").GetString("Audience"),//Audience
                ValidIssuer = AppSetting.GetSection("Secret").GetString("Issuer"),//Issuer，这两项和前面签发jwt的设置一致
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSetting.GetSection("Secret").GetString("JWT")))
            };
            options.Events = new JwtBearerEvents()
            {
                OnChallenge = context =>
                {
                    context.HandleResponse();
                    context.Response.Clear();
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = 401;
                    context.Response.WriteAsync(new { message = "授权未通过", status = false, code = 401 }.Serialize());
                    return Task.CompletedTask;
                }
            };
        });
    }
}
